package com.wjk.blogs.web;

import com.github.houbb.sensitive.word.bs.SensitiveWordBs;
import com.wjk.blogs.po.Comment;
import com.wjk.blogs.po.User;
import com.wjk.blogs.service.BlogService;
import com.wjk.blogs.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
public class commentController {

    @Autowired
    private CommentService commentService;
    @Autowired
    private BlogService blogService;

    @Value("${comment.avatar}")
    private String avator;

    @GetMapping("/comments/{id}")
    public String comments(@PathVariable Long id, Model model){
        model.addAttribute("comments",commentService.listCommentByBlogId(id));
        return "blog :: commentList";
    }

    @PostMapping("/comments")
    @ResponseBody
    public String post(@RequestBody Comment comment , HttpSession session){
        Long blogId = comment.getBlog().getId();
        comment.setBlog(blogService.getBlog(blogId));
        User user = (User) session.getAttribute("user");
        if (user != null){
            comment.setPicture(user.getPicture());
            comment.setAdminComment(true);
            comment.setNickname(user.getNickname());
        }else{
            comment.setPicture(avator);
        }
        comment.setPicture(avator);

        //敏感词过滤
        String commentC=comment.getContent();
        String result= SensitiveWordBs.newInstance().replace(commentC,'0');
        comment.setContent(result);

        commentService.saveComment(comment);
        return "redirect:/comments/" + blogId;
    }
}
